import { Form, Drawer, Input, Select, Upload, Button, message, Icon, Tooltip } from 'antd';
import React from 'react';
import { quickEntryAdd, quickEntryDetail, quickEntryEdit } from '@/services/quickEntry';

class EditQuickModal extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      visible: false,
      imgUrl: '',
      imgName: '',
      userTypeChecks: ['all'],
      submitLoading: false,
      detail: null,
      id: null,
      isImgOk: true
    }
  }

  componentDidMount() {
    if (this.props.onRef) {
      this.props.onRef(this)
    }
  }

  initOpen = row => {
    this.setState({ visible: true, detail: row }, () => {
      if (row) {
        this.getEntryDetail();
      }
    })
  }

  /* 获取详情 */
  getEntryDetail = async () => {
    const { detail } = this.state;
    const res = await quickEntryDetail({ id: detail.id })
    const userTypeList = res.userTypeList ? res.userTypeList.map(item => item.userTypeId) : [];
    if (userTypeList.length === 0) {
      userTypeList.push('all');
    }
    this.props.form.setFieldsValue({
      entryName: res.entryName,
      userType: userTypeList,
      imgUrl: res.imgUrl,
      urlPath: res.urlPath
    })
    this.setState({
      userTypeChecks: userTypeList,
      imgUrl: res.imgUrl,
      imgName: res.imgName,
    });
  }

  /* 上传图片之前 */
  beforeUpload = file => {
    const b = /\.(png|jpg|jpeg|gif|bmp|tif|ico|webp)$/;
    const a = file.name.toLowerCase();

    const pig = b.test(a);
    const isJPG = file.type;
    const isLt2M = file.size / 1024 / 1024 < 2;

    if (!pig) {
      if (!isLt2M) {
        message.error('请上传小于2M的图片');
      } else {
        message.error('请上传图片格式');
      }
    } else if (!isLt2M) {
      message.error('请上传小于2M的图片');
    }
    return isJPG && isLt2M && pig;
  };

  /* 修改上传图片 */
  handleChangeImage = info => {
    if (info.file.status === 'done') {
      this.setState({
        imgUrl: info.file.response.url ? info.file.response.url : '',
        imgName: info.file.response.original ? info.file.response.original : '',
        isImgOk: true
      })
    }
  }

  /* 关闭弹窗 */
  cancelModal = () => {
    this.props.form.resetFields();
    this.setState({
      visible: false,
      imgUrl: '',
      imgName: '',
      userTypeChecks: ['all'],
      submitLoading: false,
      detail: null,
      isImgOk: true
    })
  }

  /* 选择用户类型 */
  changeUserType = (value) => {
    let { userTypeChecks } = this.state;
    // 选择了其他的用户类型 又选择了全部类型 则需要删掉其他的用户类型 只保留全部类型
    if (value === 'all') {
      this.props.form.setFieldsValue({ userType: ['all'] });
      userTypeChecks = ['all'];
    } else {
      userTypeChecks.push(value);
    };
    this.setState({ userTypeChecks })
  }

  /* 去掉用户类型的选择 */
  deselectUserType = value => {
    if (value === 'all') {
      this.setState({ userTypeChecks: [] })
    }
  }

  /* 保存/编辑标签基础信息前校验 */
  doSubmitForm = () => {
    const that = this;
    const { imgUrl, imgName, id } = that.state;
    const { applicationId } = that.props;
    that.props.form.validateFields((errors, values) => {
      if (!errors) {
        if (!imgUrl) {
          that.setState({ isImgOk: false });
          return false;
        };
        const userTypeIdList = values.userType ? values.userType : [];
        const obj = {
          entryName: values.entryName,
          imgUrl,
          imgName,
          applicationId,
          userTypeIdList: userTypeIdList.indexOf('all') > -1 ? [] : userTypeIdList,
          urlPath: values.urlPath,
        };
        that.doSubmitFetch(obj)
      }
    })
  }

  /* 新增/编辑 请求接口 */
  doSubmitFetch = async (obj) => {
    const that = this;
    const { detail } = that.state;
    let res = {};
    if (detail) {
      /* 编辑 */
      obj.id = detail.id;
      res = await quickEntryEdit(obj);
    } else {
      /* 新增 */
      res = await quickEntryAdd(obj);
    };
    message.info(res.msg);
    that.cancelModal();
    that.props.refreshTableList();
  }

  render() {
    const { getFieldDecorator } = this.props.form;
    const { applicationId, userList } = this.props;
    const { visible, imgUrl, userTypeChecks, isImgOk } = this.state;
    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 19 },
      },
    };
    const renderLabel = (label, tip) => {
      return (
        <label>
          {label}
          <Tooltip placement="topLeft" title={tip}>
            <Icon type="question-circle" style={{ verticalAlign: 'baseline', margin: '0 5px' }} />
          </Tooltip>
        </label>
      )
    }

    return (
      <div>
        <Drawer
          title="快捷入口添加/编辑"
          visible={visible}
          width={650}
          onClose={this.cancelModal}
        >
          <Form {...formItemLayout}>
            <Form.Item label="入口名称">
              {
                getFieldDecorator('entryName', { rules: [{ required: true, message: '请填写分类标签' }] })(
                  <Input maxLength={6} />
                )
              }
            </Form.Item>
            <Form.Item label="图片">
              {
                getFieldDecorator('imgUrl', { rules: [{ required: true, message: '请上传图片' }] })(
                  <Upload
                    name="file"
                    listType="picture"
                    className="avatar-uploader"
                    showUploadList={false}
                    action="/cloud/file/upload"
                    beforeUpload={this.beforeUpload}
                    onChange={this.handleChangeImage}
                    accept=".png,.jpg,.jpeg,.gif,.bmp,.tif,.ico,.webp"
                  >
                    {
                      imgUrl ?
                        <img src={imgUrl} style={{ width: 50, height: 50, marginRight: 10 }} /> : ''
                    }
                    <Button>
                      {imgUrl ? '重新上传' : '上传图片'}
                    </Button>
                  </Upload>
                )
              }
              {
                isImgOk ? '' : <div className="ant-form-explain" style={{ color: '#f5222d' }}>请上传图片</div>
              }

            </Form.Item>
            <Form.Item label={renderLabel('链接地址', '用户点击该入口卡片后将打开该链接页面')}>
              {
                getFieldDecorator('urlPath', { initialValue: 'http://', rules: [{ required: true, message: '请填写链接地址' }] })(
                  <Input maxLength={500} />
                )
              }
            </Form.Item>
            <Form.Item label={renderLabel('适用用户类型', '选择设置哪种类型的用户可以看到该入口卡片')}>
              {
                getFieldDecorator('userType', { initialValue: ['all'], rules: [{ required: true, message: '请选择用户类型' }] })(
                  <Select mode="multiple" onSelect={this.changeUserType} onDeselect={this.deselectUserType}>
                    <Select.Option value="all">默认类型</Select.Option>
                    {
                      userList.map((item, index) => {
                        return <Select.Option disabled={userTypeChecks.indexOf('all') != -1} value={item.id} key={item.id}>{item.tagName}</Select.Option>
                      })
                    }
                  </Select>
                )
              }
            </Form.Item>
            
          </Form>

          <div
            style={{
              position: 'absolute',
              right: 0,
              bottom: 0,
              width: '100%',
              borderTop: '1px solid #e9e9e9',
              padding: '10px 16px',
              background: '#fff',
              textAlign: 'right',
            }}
          >
            <Button onClick={this.cancelModal} style={{ marginRight: 8 }}>
              取消
            </Button>
            <Button onClick={this.doSubmitForm} type="primary">
              确定
            </Button>
          </div>
        </Drawer>

      </div>
    );
  }


}

export default Form.create()(EditQuickModal)
